﻿//1721. 交换链表中的节点
//给你链表的头节点 head 和一个整数 k 。
//交换 链表正数第 k 个节点和倒数第 k 个节点的值后，返回链表的头节点（链表 从 1 开始索引）。


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapNodes(ListNode* head, int k)
    {
        if (!head)
            return head;
        ListNode hair;
        hair.next = head;
        auto fast = &hair;
        auto slow = &hair;
        while (--k)
        {
            fast = fast->next;
        }
        ListNode* prev = fast;
        fast = fast->next;
        while (fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }
        int temp = slow->next->val;
        slow->next->val = prev->next->val;
        prev->next->val = temp;
        return hair.next;
    }
};